package com.hedl.practice.diyJava.reflex.method_access;

import com.hedl.practice.diyJava.reflex.method_access.utils.Person;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class Task {
    // 作业练习
    public static void main(String[] args) {
        String name = "Xiao Hong";
        int age = 20;

        Person p = new Person();
        Method[] m = p.getClass().getMethods();

        Task t = new Task();
        t.studyReflex(name,age,m,p);
        System.out.println("name-->"+p.getName());
        System.out.println("age-->"+p.getAge());
    }
    private void studyReflex(String name,int age,Method[] m,Object p){
        for (Method method:m){
            if (method.getName() == "setName"){
                try {
                    method.invoke(p,name);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            } else if (method.getName() == "setAge") {
                try {
                    method.invoke(p,age);
                } catch (IllegalAccessException e) {
                    throw new RuntimeException(e);
                } catch (InvocationTargetException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
